package com.ncmmall.api.apis.mall;


import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.params.GoodsCommentDTO;
import com.ncmmall.api.params.GoodsCommentImageDTO;
import com.ncmmall.api.params.SupplierIssuingDTO;
import com.ncmmall.api.params.SupplierIssuingDetailDTO;
import com.ncmmall.api.security.Securitys;
import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.application.business.order.OrderApplication;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.GoodsRepository;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.comment.GoodsComment;
import com.ncmmall.domain.business.goods.comment.GoodsCommentImage;
import com.ncmmall.domain.business.goods.comment.QGoodsComment;
import com.ncmmall.domain.business.goods.image.GoodsImage;
import com.ncmmall.domain.business.goods.sku.GoodsSku;
import com.ncmmall.domain.business.goods.sku.QGoodsSku;
import com.ncmmall.domain.business.order.OrderDetail;
import com.ncmmall.domain.business.order.QOrderDetail;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * 商品接口
 */
@RestController
@RequestMapping(value = "/goods")
public class GoodsApi {

    private final Logger logger = LoggerFactory.getLogger(GoodsApi.class);

    @Autowired
    private GoodsApplication goodsApplication;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private OrderApplication orderApplication;

    @Autowired
    private QueryChannelService queryChannelService;

    @Value("${store.domain}")
    private String storeDomain;

    /**
     * 商品详情
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public Result detail(HttpServletRequest request, Long id) {
        Result result = new Result();
        try {

            if (id == null) {
                return result.fail().setMsg("商品id不能为空");
            }

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
            Requires.notNull(goods, "商品不存在");

            for (GoodsImage image : goods.getImages()) {
                image.setName(storeDomain + "/uploads/" + image.getName());
            }

            if (StringUtils.isNotBlank(goods.getDefaultImage())) {
                goods.setDefaultImage(storeDomain + "/uploads/" + goods.getDefaultImage());
            }

            //收藏状态
            if (Securitys.isLogin(request)) {
                WebUser user = Securitys.user(request);
                int count = queryChannelService.selectCount("select count(*) from mall_goods_collect where goods_id = :gid and member_id = :mid", ImmutableMap.of("gid", id, "mid", user.getId()));
                goods.setCollect(count > 0);
            }

            //评论
            Long commentCount = queryChannelService.findCount(QGoodsComment.goodsComment.goods.id.eq(id)
                    .and(QGoodsComment.goodsComment.platformType.eq(1))
                    .and(QGoodsComment.goodsComment.status.eq(2)), GoodsComment.class);

            GoodsComment comment = goodsComments(id);

            Map<String, Object> shop = new HashMap<>();
            shop.put("name", Strings.isNullOrEmpty(goods.getMerchant().getShopName()) ? "" : goods.getMerchant().getShopName());
            shop.put("id", goods.getMerchant().getId());
            shop.put("logo", Strings.isNullOrEmpty(goods.getMerchant().getAvatar()) ? "" : storeDomain + "/avatar/" + goods.getMerchant().getAvatar());
            shop.put("selfSupport", goods.getMerchant().getSelfSupport());

            Map<String, Object> data = new HashMap<>();
            data.put("goods", goods);
            data.put("commentCount", commentCount);
            data.put("comment", comment);
            data.put("serviceTelephone", goods.getMerchant().getMobile());
            data.put("shop", shop);
            data.put("systemTime", System.currentTimeMillis());

            return result.ok().inject(data);

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {

            logger.error("[获取商品详情异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    /**
     * 一件代发
     */
    @RequestMapping(value = "/issuing", method = RequestMethod.POST)
    @ResponseBody
    public Result issuing(HttpServletRequest request, @RequestBody SupplierIssuingDTO params) {
        Result result = new Result();
        try {
            WebUser merchant = Securitys.user(request);
            Goods oldGoods = queryChannelService.findFirst("select g from Goods g where g.issuingGoods.id = :id and g.merchant.id =:mid ",
                    ImmutableMap.of("id", params.getId(), "mid", merchant.getId()), Goods.class);

            if (null != oldGoods) {
                if (oldGoods.getStatus() == 5) {
                    oldGoods.setStatus(3);
                    goodsRepository.save(oldGoods);
                    return result.ok().inject(ImmutableMap.of("id", oldGoods.getId()));
                } else {
                    return result.fail().setMsg("您已一件代发过该商品");
                }
            }

            Goods supplierGoods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
            Requires.notNull(supplierGoods, "商品不存在");

            Goods goods = new Goods();
            BeanUtils.copyProperties(goods, supplierGoods);
            goods.setMerchant(merchant);
            goods.setIsSupplier(0);
            goods.setSalesVolume(0);
            goods.setIssuingGoods(supplierGoods);
            goods.setDefaultPrice(params.getDefaultPrice());
            goods.setMarketPrice(params.getMarketPrice());

            List<GoodsSku> skus = Lists.newArrayList();

            for (SupplierIssuingDetailDTO item : params.getDetails()) {
                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(item.getId()), GoodsSku.class);
                sku.setPrice(item.getPrice());
                skus.add(sku);
            }

            Goods data = goodsApplication.issuing(goods, skus);

            return result.ok().inject(ImmutableMap.of("id", data.getId()));

        } catch (IllegalArgumentException e) {
            logger.error("[一件代发商品异常]", e);
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("[一件代发商品异常]", e);
            return result.fail().setMsg("网络连接失败");
        }
    }

    /**
     * 获取商品的第一条评论
     *
     * @param id 商品id
     */
    private GoodsComment goodsComments(long id) {
        QueryPageRequest page = new QueryPageRequest().setPageSize(1).setParams(ImmutableMap.of("id", id));
        QueryPage<GoodsComment> comments = queryChannelService.findPage("select c from GoodsComment c where c.status = 2 and c.platformType = 1 and c.goods.id = :id order by c.createTime desc ", page, GoodsComment.class);
        GoodsComment comment = comments.getResult().size() > 0 ? comments.getResult().get(0) : null;
        if (null != comment) {
            comment.setMember(Securitys.cleanUser(comment.getMember()));
            for (GoodsCommentImage image : comment.getImages()) {
                image.setName(storeDomain + "/uploads/" + image.getName());
            }

        }
        return comment;
    }

    /**
     * 商品评价
     */
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    @ResponseBody
    public Result comment(HttpServletRequest request, @RequestBody GoodsCommentDTO params) {
        Result result = new Result();
        try {

            WebUser member = Securitys.user(request);

            GoodsComment comment = new GoodsComment();
            comment.setGoods(queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class));
            comment.setStarLever(params.getStarLever());
            comment.setContent(params.getContent());
            comment.setPlatformType(1);

            List<GoodsCommentImage> images = Lists.newArrayList();
            for (GoodsCommentImageDTO item : params.getImages()) {
                GoodsCommentImage image = new GoodsCommentImage();
                image.setName(item.getName());
                images.add(image);
            }

            comment.setImages(images);

            OrderDetail orderDetail = queryChannelService.findOne(QOrderDetail.orderDetail.id.eq(params.getOrderDetailId()), OrderDetail.class);

            orderApplication.comment(member, comment, orderDetail);

            return result.ok();

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {

            logger.error("[获取商品详情异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    /**
     * 评论列表
     */
    @GetMapping("/comments")
    @ResponseBody
    public Result comments(@RequestParam(defaultValue = "1") int pageNo,
                           @RequestParam(defaultValue = "20") int pageSize, Long id) {
        Result result = new Result();
        try {
            Requires.notNull(id, "id不能为空");
            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);

            String hql = "select c from GoodsComment c where c.platformType = 1 and c.status = 2 and c.goods.id = :id order by c.createTime desc ";
            QueryPage<GoodsComment> page = queryChannelService.findPage(hql, pageRequest.setParams(params), GoodsComment.class);

            for (GoodsComment comment : page.getResult()) {
                WebUser member = comment.getMember();
                comment.setMember(Securitys.cleanUser(member));
                for (GoodsCommentImage detail : comment.getImages()) {
                    detail.setName(storeDomain + "/uploads/" + detail.getName());
                }
            }

            return result.ok().inject(ImmutableMap.of("page", page));

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("[评论列表异常]", e);
            return result.fail().setMsg("网络请求异常");
        }
    }


}
